from threading import Thread
import os,re,time,threading,math
import requests


class Main():
    def __init__(self,url):
        self.thread_list = []
        self.thread_num = 100
        self.temp = 'temp/'  # 临时下载目录
        self.work_dir = os.getcwd()
        self.semaphore = threading.Semaphore(self.thread_num)# 初始化信号量，数量为100
        self.url = url
        self.baseUrl = self.url.replace('index.m3u8', '')
        self.headers = {
            'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.116 Safari/537.36'
        }
        self.ts_len = len(self.get_ts_name())
        self.mkdir_ts_temp()
        super().__init__()  # 继承父类初始化方法
        pass

    def start(self):
        for i in range(self.thread_num):  # 100个线程同时启动
            t = Thread()
            t.setName(i) #设置线程名称
            self.thread_list.append(t)
        for t in self.thread_list:  # 100个线程同时启动
            t.setDaemon(True)
            thread_id = t.getName()
            self.aa()
            self.down_ts_file(thread_id)
            print("\n开始线程："+ str(t))
            t.start()
        for t in self.thread_list:  # 100个线程同时启动
            t.join()  # 主线程等待子线程执行完毕后才退出
        pass

    def aa(self):
        print('打印功能部分')
        pass

    def down_ts_file(self,thread_id):
        step = math.ceil(self.ts_len / self.thread_num)
        for i in range(step):
            print(str(thread_id)+'号线程,执行第'+str(i)+'次')

    def get_ts_name(self):
        r = requests.get(self.url, headers=self.headers)
        all_data = r.text
        text_string = all_data.split("\n")
        if r.status_code != 200:
            print('请确认地址正确并可以正常下载')
        if text_string[0] != '#EXTM3U':
            print(u"非正确m3u8链接")
        ts_name = [i for i in text_string if not i.startswith('#')]
        ts_time = [float(re.findall('[.\d]+', i)[0]) for i in text_string if i.startswith('#EXTINF')]
        ts_name = [i for i in ts_name if (len(str(i)) != 0)] # 清除数组空元素
        if len(ts_name) != len(ts_time):
            print('m3u8内ts文件和时间戳不匹配')
        return ts_name

    # 用来保存ts文件
    def mkdir_ts_temp(self):
        file_dir = os.path.join(self.work_dir, self.temp)
        if not os.path.exists(file_dir):
            os.mkdir(file_dir)
            print("下载目录创建完毕\n")

if __name__ == '__main__':
    start_time = time.time()
    print('主线程开始：', threading.current_thread().name)
    link = 'https://ckcdnc1.cdn2020.com/video/m3u8/2020/03/07/c19957d0/index.m3u8'
    obj = Main(link)
    obj.start()
    print('主线程结束！', threading.current_thread().name)
    print('主线程结束，一共用时：', time.time() - start_time)
